package com.party.jackclientandroid.controller;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.party.jackclientandroid.R;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.PayService;
import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.api.UserService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CommonResult;
import com.party.jackclientandroid.bean.PayResult;
import com.party.jackclientandroid.bean.User;
import com.party.jackclientandroid.bean.WxPaymentBean;
import com.party.jackclientandroid.event.PayResultEvent;
import com.party.jackclientandroid.pay.alipay.Alipay;
import com.party.jackclientandroid.ui_home.activity.DiscountPayBillActivity;
import com.party.jackclientandroid.ui_home.activity.GroupBuyCouponDetailActivity;
import com.party.jackclientandroid.ui_mine.my_wallet.BindingAccountZfbActivity;
import com.party.jackclientandroid.ui_mine.my_wallet.RealNameAuthenticationActivity;
import com.party.jackclientandroid.ui_order.SubmitOrderActivity;
import com.party.jackclientandroid.utils.NetworkUtils;
import com.party.jackclientandroid.view.dialog.AuthDialog;
import com.party.jackclientandroid.view.dialog.ConfirmDialog;
import com.party.jackclientandroid.widget.InputPayPasswordView;
import com.party.jackclientandroid.wxapi.WXPayUtils;
import com.zyyoona7.popup.EasyPopup;

import org.greenrobot.eventbus.EventBus;

/**
 * 订单-提交订单-支付界面
 */
public class PayController extends BaseController {
    PayService payService;
    UserService userService;
    private BaseActivity mActivity;
    private EasyPopup payChoosePopupWindow, inputPayPwdPopupWindow;

    private View view;
    private String orderId;
    private final int PAY_TYPE_ZHIFUBAO = 1, PAY_TYPE_WEIXIN = 2, PAY_TYPE_MY_WALLET = 3;
    private int currChoosePayType/* = PAY_TYPE_MY_WALLET*/;
    private ImageView my_wallet_iv, weixin_pay_iv, zhifubao_pay_iv;
    private Button pay_btn;
    private LinearLayout my_wallet_pay_ll, weixin_pay_ll, zhifubao_pay_ll;
    private String walletBalance;
    private String xiaPinCoin;
    private TextView pay_account_tv, wallet_balance_tv;
    private int isAuthentication;
    private int isPassword;
    private PayController walletController;

    public PayController(BaseActivity activity, View view) {
        super(activity);
        userService = new UserService(activity);
        payService = new PayService(activity);
        mActivity = activity;
        this.view = view;
        initView();
    }

    private void initView() {
        User user = mApplication.getUser();
        isAuthentication = user.getIsAuthentication();
        isPassword = user.getIsPassword();
        View layout = mActivity.getLayoutInflater().inflate(R.layout.choose_pay_type_popup, null);
        wallet_balance_tv = layout.findViewById(R.id.wallet_balance_tv);
        pay_account_tv = layout.findViewById(R.id.pay_account_tv);
        setButtonListeners(layout);

        layout.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (payChoosePopupWindow != null) {
                    payChoosePopupWindow.dismiss();
                    payChoosePopupWindow = null;
                }
                return true;
            }
            return false;
        });

        payChoosePopupWindow = EasyPopup.create(mActivity)
                .setContentView(layout)
                .setAnimationStyle(R.style.Popupwindow)
                .setBackgroundDimEnable(true)
                .setDimValue(0.4f)
                .setDimColor(Color.GRAY)
                .setFocusAndOutsideEnable(true)
                .setWidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
                .apply();
    }


    /**
     * 微信支付,先从后台服务器获取微信支付参数
     *
     * @param orderId
     */
    private void doWxPayWork(String orderId) {
        String ip = NetworkUtils.getIPAddress(baseActivity.get());
        if (TextUtils.isEmpty(ip)) {
            ip = "127.0.0.1";
        }
        baseActivity.get().addDisposableIoMain(payService.wxPayOrder(orderId, ip), new DefaultConsumer<WxPaymentBean>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<WxPaymentBean> result) {
                if (result.getData().getPrepayId() == null) {
                    mActivity.showToast("微信支付失败");
                }
                doWxPay(result.getData());
//                mActivity.hideAlertDialog();
            }
        });
    }

    /**
     * 支付宝支付,先从后台服务器获取支付宝支付参数
     *
     * @param orderId
     */
    private void doAliPayWork(String orderId) {
        String ip = NetworkUtils.getIPAddress(baseActivity.get());
        if (TextUtils.isEmpty(ip)) {
            ip = "127.0.0.1";
        }
        baseActivity.get().addDisposableIoMain(payService.aliPayOrder(orderId, ip), new DefaultConsumer<String>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<String> result) {
                doAliPay(result.getData());
//                mActivity.hideAlertDialog();
            }
        });
    }

    /**
     * 余额支付
     *
     * @param orderId
     */
//    public void doMyWalletPay(final long orderId, String payPwd, final int goodsType, @Nullable final int finalNum, @Nullable final View view) {
    private void doMyWalletPay(String orderId, String payPwd) {
        baseActivity.get().addDisposableIoMain(payService.doMyWalletPayOrder(orderId, payPwd), new DefaultConsumer<PayResult>(mApplication) {
            @Override
            public void operateError(String message) {
                super.operateError(message);
                if (inputPassFinish != null) {
                    inputPassFinish.payFail(message);
                } else {
                    DialogController.showConfirmDialog(mActivity, "支付失败", "");
                }
            }

            @Override
            public void operateSuccess(BaseResult<PayResult> result) {
                inputPayPwdPopupWindow.dismiss();
                if (inputPassFinish != null) {
                    inputPassFinish.payOk(result);
                } else {
                    DialogController.showMustConfirmDialog(mActivity, "支付成功", "您已支付" + finalPrice + "元", (View v) -> {
                        mActivity.finish();
                    });
                }

            }
//                switch (goodsType) {
//
//                    case Constant.GOODS_TYPE_SECOND_KILL:
//                    case Constant.GOODS_TYPE_REPLACE_MONEY:
//                        Intent intent = new Intent(mActivity, ReplaceMoneyCouponBuySuccessActivity.class);
//                        intent.putExtra("order_id", orderId);
//                        mActivity.startActivity(intent);
//                        mActivity.finish();
//                        break;
//                    case Constant.GOODS_TYPE_SPELLING_GROUP:
//                    case Constant.GOODS_TYPE_GROUP_BUY:
//                        if (finalNum > 1) {
//                            Intent intent1 = new Intent(mActivity, GroupBuyCouponBuySuccessMoreThanOneActivity.class);
//                            intent1.putExtra("order_id", orderId);
//                            mActivity.startActivity(intent1);
//                        } else {
//                            Intent intent1 = new Intent(mActivity, GroupBuyCouponBuySuccessActivity.class);
//                            intent1.putExtra("order_id", orderId);
//                            mActivity.startActivity(intent1);
//                        }
//                        mActivity.finish();
//                        break;
//                    case Constant.GOODS_TYPE_VIP:
//                        ((Button) view).setText("已开通");
//                        break;
//                    case Constant.GOODS_TYPE_OTHER:
//                        mActivity.finish();
//                }
        });
    }

    /**
     * 拉起微信支付
     *
     * @param wxPaymentBean
     */
    private void doWxPay(WxPaymentBean wxPaymentBean) {
        wxPaymentBean.setPackageValue("Sign=WXPay");
        WXPayUtils.WXPayBuilder builder = new WXPayUtils.WXPayBuilder();
        builder.setAppId(wxPaymentBean.getAppId())
                .setPartnerId(wxPaymentBean.getPartnerId())
                .setPrepayId(wxPaymentBean.getPrepayId())
                .setPackageValue(wxPaymentBean.getPackageValue())
                .setNonceStr(wxPaymentBean.getNonceStr())
                .setTimeStamp(wxPaymentBean.getTimeStamp())
                .setSign(wxPaymentBean.getSign())
                .build().toWXPayNotSign(baseActivity.get());
    }

    /**
     * 拉起支付宝支付
     *
     * @param params
     */
    private void doAliPay(String params) {
        Alipay alipay = new Alipay(baseActivity.get(), params, new Alipay.AlipayResultCallBack() {
            @Override
            public void onSuccess() {
                EventBus.getDefault().post(new PayResultEvent(1, 1));
            }

            @Override
            public void onDealing() {
                System.out.println();
            }

            @Override
            public void onError(int error_code) {
                EventBus.getDefault().post(new PayResultEvent(1, -1));
            }

            @Override
            public void onCancel() {
                EventBus.getDefault().post(new PayResultEvent(1, 0));
            }
        });
        alipay.doPay();
    }

    String tipText, finalPrice;

    /**
     * 设置付款方式的 标题
     */
    public void setPayTipTitle(String payTipTitle) {
        tipText = payTipTitle;
    }

    public interface LoadingData {
        void loadingSuccess(CommonResult bean);
    }

    public void preloading(LoadingData listener) {
        mActivity.addDisposableIoMain(userService.getUserWallet(), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> baseBean) {
                walletBalance = baseBean.getData().getMoney();
                xiaPinCoin = baseBean.getData().getXiapinCoin();
                listener.loadingSuccess(baseBean.getData());
            }
        });
    }

    public void showPayMethod(String finalPrice, String orderId, View.OnClickListener listener) {
        if (finalPrice == null) {
            mActivity.showToast("请输入金额");
            return;
        }
        tipText = "支付金额：" + finalPrice + "元";
        this.finalPrice = finalPrice;
        pay_account_tv.setText(tipText);
        this.orderId = orderId;
        if (walletBalance == null) {
            mActivity.showLoadingDialog("正在处理");
            mActivity.addDisposableIoMain(userService.getUserWallet(), new DefaultConsumer<CommonResult>(mApplication) {
                @Override
                public void operateSuccess(BaseResult<CommonResult> baseBean) {
                    walletBalance = baseBean.getData().getMoney();
                    xiaPinCoin = baseBean.getData().getMoney();
                    wallet_balance_tv.setText("（余额:" + walletBalance + "元）");
                    showSelectPayMethod(listener);
                    mActivity.hideAlertDialog();
                }
            });
        } else {
            wallet_balance_tv.setText("（余额:" + walletBalance + "元）");
            showSelectPayMethod(listener);
        }
    }

    /**
     * 打开钱包
     */
    public void showSelectPayMethod(View.OnClickListener listener) {
        if (mActivity.helper != null) mActivity.helper.showContent();
        payChoosePopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        mActivity.hideSoftInput(mActivity, view);
        pay_btn.setOnClickListener((View v) -> {
            if (isAuthentication != 1 && isPassword != 1) {
                DialogController.showAuthTip(mActivity, (View vv) -> {
                    mActivity.startActivity(BindingAccountZfbActivity.class);
                });
            } else if (orderId == null) {
                listener.onClick(v);
            } else if (orderId != null) {
                pay(orderId);
            }

            if (payChoosePopupWindow != null && payChoosePopupWindow.isShowing()) {
                payChoosePopupWindow.dismiss();
            }
        });
    }

    public void pay(String orderId) {
        switch (currChoosePayType) {
            case PAY_TYPE_MY_WALLET:
                showInputPwdPopup(orderId);
                break;
            case PAY_TYPE_WEIXIN:
                doWxPayWork(orderId);
                break;
            case PAY_TYPE_ZHIFUBAO:
                doAliPayWork(orderId);
                break;
        }
    }

    private void setButtonListeners(View layout) {
        ImageView dismiss_iv = layout.findViewById(R.id.dismiss_iv);
        TextView pay_account_tv = layout.findViewById(R.id.pay_account_tv);
        my_wallet_iv = layout.findViewById(R.id.my_wallet_iv);
        weixin_pay_iv = layout.findViewById(R.id.weixin_pay_iv);
        zhifubao_pay_iv = layout.findViewById(R.id.zhifubao_pay_iv);
        my_wallet_pay_ll = layout.findViewById(R.id.my_wallet_pay_ll);
        weixin_pay_ll = layout.findViewById(R.id.weixin_pay_ll);
        zhifubao_pay_ll = layout.findViewById(R.id.zhifubao_pay_ll);
        pay_btn = layout.findViewById(R.id.pay_btn);

        currChoosePayType = PAY_TYPE_MY_WALLET;
        zhifubao_pay_iv.setImageResource(R.mipmap.pay_type_choose_normal);
        my_wallet_iv.setImageResource(R.mipmap.pay_type_choose_selected);
        weixin_pay_iv.setImageResource(R.mipmap.pay_type_choose_normal);


        dismiss_iv.setOnClickListener((View v) -> {

            if (payChoosePopupWindow != null && payChoosePopupWindow.isShowing()) {
                payChoosePopupWindow.dismiss();
            }
        });


        pay_account_tv.setOnClickListener(onClickListener);
        my_wallet_pay_ll.setOnClickListener(onClickListener);
        weixin_pay_ll.setOnClickListener(onClickListener);
        zhifubao_pay_ll.setOnClickListener(onClickListener);

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.my_wallet_pay_ll:
                    currChoosePayType = PAY_TYPE_MY_WALLET;
                    zhifubao_pay_iv.setImageResource(R.mipmap.pay_type_choose_normal);
                    my_wallet_iv.setImageResource(R.mipmap.pay_type_choose_selected);
                    weixin_pay_iv.setImageResource(R.mipmap.pay_type_choose_normal);
                    break;
                case R.id.weixin_pay_ll:
                    if (finalPrice == null || Double.parseDouble(finalPrice) == 0) {
                        mActivity.showToast("0只有使用钱包支付");
                        return;
                    }
                    currChoosePayType = PAY_TYPE_WEIXIN;
                    zhifubao_pay_iv.setImageResource(R.mipmap.pay_type_choose_normal);
                    my_wallet_iv.setImageResource(R.mipmap.pay_type_choose_normal);
                    weixin_pay_iv.setImageResource(R.mipmap.pay_type_choose_selected);
                    break;
                case R.id.zhifubao_pay_ll:
                    if (finalPrice == null || Double.parseDouble(finalPrice) == 0) {
                        mActivity.showToast("0只有使用钱包支付");
                        return;
                    }
                    currChoosePayType = PAY_TYPE_ZHIFUBAO;
                    zhifubao_pay_iv.setImageResource(R.mipmap.pay_type_choose_selected);
                    my_wallet_iv.setImageResource(R.mipmap.pay_type_choose_normal);
                    weixin_pay_iv.setImageResource(R.mipmap.pay_type_choose_normal);
                    break;
            }
        }
    };


    public void showInputPwdPopup(String orderId) {
        inputPayPwdPopupWindow = InputPayPasswordView.showPop(mActivity, view, (String password) -> {
            doMyWalletPay(orderId, password);
        });
    }

    DiscountPayBillActivity.PayCompleteListener inputPassFinish;

    public void setInputPassFinish(DiscountPayBillActivity.PayCompleteListener inputPassFinish) {
        this.inputPassFinish = inputPassFinish;
    }


}
